package com.weather;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.view.LineChartView;

public class ChartView extends AppCompatActivity {

    private TabLayout tabs;
    private ViewPager vpView;
    private LayoutInflater mInflater;
    private View view1;

    private Button local;

    //选项卡视图集合
    List<String> mTitleList = new ArrayList<>();
    //选项卡标题集合
    List<View> mViewList = new ArrayList<>();

    //线形图的属性
    //横轴的刻度
    String[] lineData = new String[3];
    //温度数据点
    int[] temperature = new int[3];

    LocationManager lm;

    ArrayList<Weather> arrayList;


    //数据点的值
    List<PointValue> pointValues = new ArrayList<PointValue>();
    List<AxisValue> axisValues = new ArrayList<AxisValue>();

    LineChartView lineChartView;

    private static String[] PERMISSIONS_STORGE = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
    //权限的请求编码
    private static int REQUEST_PERMISSION_CODE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart_view);

        if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
            if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=
                    PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,PERMISSIONS_STORGE,REQUEST_PERMISSION_CODE);
            }
        }

        local = (Button) findViewById(R.id.button1);

        tabs = (TabLayout) findViewById(R.id.tabs);
        vpView = (ViewPager) findViewById(R.id.vp_view);

        mInflater = LayoutInflater.from(this);


        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!isGpsAble(lm)) {
            Toast.makeText(ChartView.this, "请先打开位置信息！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            ChartView.this.finish();
        }
        Location lc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        final String localCity = getLocalCity(lc);
        setDT(localCity);
        local.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view1 = mInflater.inflate(R.layout.line_view, null);

                mViewList.add(view1);
                mTitleList.add(localCity + "气温变化图");

                tabs.setTabMode(TabLayout.MODE_FIXED);
                tabs.addTab(tabs.newTab().setText(mTitleList.get(0)));
                ViewPagerAdapter mAdapter = new ViewPagerAdapter(mViewList, mTitleList);
                vpView.setAdapter(mAdapter);

                tabs.setupWithViewPager(vpView);
                tabs.setTabsFromPagerAdapter(mAdapter);
                //线形图的完善
                lineChartView = (LineChartView) view1.findViewById(R.id.line_view);
                //设置X轴
                setAxisLables();
                //设置数值坐标点
                setAxisPoinrs();
                //线的设置
                initLineChart();
                local.setEnabled(false);
                local.setVisibility(View.INVISIBLE);
            }
        });

    }

    private String getLocalCity(Location lc) {
        String thisCity = null;

        if (lc != null) {
            Geocoder ge = new Geocoder(ChartView.this);
            List<Address> addList = null;
            try {
                //sb.append("当前城市:"+ge.getFromLocation(lc.getLatitude(),lc.getLongitude(),1).get(0).getFeatureName());
                addList = ge.getFromLocation(lc.getLatitude(), lc.getLongitude(), 1);

            } catch (IOException e) {
                e.printStackTrace();
            }
            Address ad = addList.get(0);
            thisCity = ad.getLocality();

        } else {
            Toast.makeText(ChartView.this, "定位失败", Toast.LENGTH_SHORT).show();
        }
        return thisCity;

    }

    private boolean isGpsAble(LocationManager lm) {
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ? true : false;
    }

    private void setAxisLables() {
        for (int i = 0; i < lineData.length; i++) {
            axisValues.add(new AxisValue(i).setLabel(lineData[i]));
        }
    }

    private void setAxisPoinrs() {
        for (int i = 0; i < temperature.length; i++) {
            pointValues.add(new PointValue(i, temperature[i]));
        }
    }

    private void initLineChart() {
        //线的颜色，姓张等
        Line line = new Line();
        line.setColor(Color.parseColor("#33b5e5"));
        line.setShape(ValueShape.CIRCLE);  //设置圆形数据点
        line.setCubic(false);   //设置曲线还是折线
        line.setHasLabels(true);  //增加标注


        line.setValues(pointValues);
        List<Line> lines = new ArrayList<Line>();
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //X轴
        Axis axisX = new Axis();
        axisX.setTextColor(Color.BLACK);
        axisX.setValues(axisValues);
        axisX.setHasLines(true);
        data.setAxisXBottom(axisX);
        //Y轴
        Axis axisY = new Axis();
        axisY.setTextColor(Color.BLACK);
        data.setAxisYLeft(axisY);

        lineChartView.setInteractive(true);
        lineChartView.setMaxZoom(2.0f);
        lineChartView.setLineChartData(data);
        lineChartView.setVisibility(View.VISIBLE);
    }

    private void setDT(final String city) {
        new Thread() {
            public void run() {
                try {
                    String path = "https://api.seniverse.com/v3/weather/daily.json?key=SIOCPBEqycrUpr70G&location=" +
                            city + "&language=zh-Hans&unit=c&start=0&days=5";

                    URL url = new URL(path);

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                    conn.setReadTimeout(500);
                    conn.setRequestMethod("GET");


                    if (conn.getResponseCode() == 200) {
                        InputStream in = conn.getInputStream();


                        String str = "";
                        int len = 0;
                        byte[] buffer = new byte[1024];


                        while ((len = in.read(buffer)) > 0) {
                            str += new String(buffer, 0, len);
                        }

                        arrayList = MyJson.getWeather(str);
                        runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            lineData[0] = arrayList.get(0).getDate().substring(5);
                                            temperature[0] = Integer.parseInt(arrayList.get(0).getLow());
                                            lineData[1] = arrayList.get(1).getDate().substring(5);
                                            temperature[1] = Integer.parseInt(arrayList.get(1).getLow());
                                            lineData[2] = arrayList.get(2).getDate().substring(5);
                                            temperature[2] = Integer.parseInt(arrayList.get(2).getLow());
                                        } catch (NumberFormatException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    } else {
                        // Toast.makeText(WeatherActivity.this,"请求发送失败！请重试",Toast.LENGTH_SHORT).show();
                        show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();

    }


    public void show() {
        runOnUiThread(
                new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ChartView.this, "请求发送失败！请重试", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }
}